﻿using UnityEngine;
using System.Collections;

public class BallScript : MonoBehaviour {

    private bool ballIsActive;                      //是否激活状态（激活态的可以运动）
    private Vector3 ballPosition;                   //小球的坐标（三维）
    private Vector2 ballInitialForce;               //初始作用力

    public GameObject playerObject;                 //绑定的组件，这里是玩家的挡板
    public AudioClip soundForHit;                   //碰撞时的打击音效

    // Use this for initialization
    void Start () {

        ballInitialForce = new Vector2(100.0f,300.0f);
        ballPosition = transform.position;
        ballIsActive = false;

	}
	
	// Update is called once per frame
	void Update () {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (!ballIsActive)
            {
                Rigidbody2D rigidbody2D = (Rigidbody2D)GetComponent<Rigidbody2D>();
                rigidbody2D.isKinematic = false;
                rigidbody2D.AddForce(ballInitialForce);
                ballIsActive = !ballIsActive;

            }
        }
        if (!ballIsActive && playerObject != null)
        {
            ballPosition.x = playerObject.transform.position.x;

            transform.position = ballPosition;
        }

        if (transform.position.y < -5.46)
        {
            ballIsActive = false;
            ballPosition = playerObject.transform.position;
            ballPosition.y = -4.09f;
            Rigidbody2D rigidbody2D = (Rigidbody2D)GetComponent<Rigidbody2D>();
            rigidbody2D.isKinematic = true;
            transform.position = ballPosition;

            playerObject.SendMessage("takeLife");
        }

    }
    /// <summary>
    /// 小球的2D碰撞检测
    /// </summary>
    /// <param name="collision"></param>
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (this.ballIsActive)
        {
            AudioSource audio = (AudioSource)GetComponent<AudioSource>();
            audio.PlayOneShot(soundForHit);                                     //播放一次打击音效
        }
    }
}
